package net.loyintean.pearlshell.wechat.model;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.ServletRequest;

/**
 * 微信的身份验证数据模型
 * 
 * @author Administrator
 * 
 */
public class WeChatIdentityModel {

	/**
	 * 微信加密签名。
	 */
	private static final String paramName_signature = "signature";

	/**
	 * 时间戳
	 */
	private static final String paramName_timestamp = "timestamp";

	/**
	 * 随机数
	 */
	private static final String paramName_nonce = "nonce";

	/**
	 * 随机字符串
	 */
	private static final String paramName_echostr = "echostr";

	/**
	 * 微信账号服务器设置的token，要与接口配置信息中的Token要一致，校验才能通过
	 * 
	 * @author wuyichen-ghq
	 * @since 2014-6-25
	 */
	private static String token = "loyintean";

	/**
	 * 微信加密签名。
	 */
	private String signature;

	/**
	 * 时间戳
	 */
	private String timestamp;

	/**
	 * 随机数
	 */
	private String nonce;

	/**
	 * 随机字符串
	 */
	private String echostr;

	/**
	 * 从request中获取相关数据。
	 * 
	 * @param request
	 */
	public WeChatIdentityModel(ServletRequest request) {
		super();

		assert request != null;

		// 微信加密签名 ，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		this.signature = request.getParameter(paramName_signature);
		// 时间戳
		this.timestamp = request.getParameter(paramName_timestamp);
		// 随机数
		this.nonce = request.getParameter(paramName_nonce);
		// 随机字符串
		this.echostr = request.getParameter(paramName_echostr);
	}

	/**
	 * 加密/校验流程如下：
	 * <p>
	 * 1. 将token、timestamp、nonce三个参数进行字典序排序
	 * <p>
	 * 2.将三个参数字符串拼接成一个字符串进行sha1加密
	 * <p>
	 * 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	 * 
	 * @author wuyichen-ghq
	 * @since 2014-6-25
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public boolean checkSignature() {
		if (token == null || timestamp == null || nonce == null) {
			return false;
		}

		String[] arr = new String[] { token, timestamp, nonce };
		// 步骤1
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 步骤二
			byte[] digest = md.digest(content.toString().getBytes());
			content = null;

			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			tmpStr = null;
		}

		// 步骤三
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @author wuyichen-ghq
	 * @since 2014-6-25
	 * @param digest
	 * @return
	 */
	private final String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换成十六进制字符串
	 * 
	 * @author wuyichen-ghq
	 * @since 2014-6-25
	 * @param b
	 * @return
	 */
	private final String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("WeChatModel [");
		if (signature != null) {
			builder.append("signature=");
			builder.append(signature);
			builder.append(", ");
		}
		if (timestamp != null) {
			builder.append("timestamp=");
			builder.append(timestamp);
			builder.append(", ");
		}
		if (nonce != null) {
			builder.append("nonce=");
			builder.append(nonce);
			builder.append(", ");
		}
		if (echostr != null) {
			builder.append("echostr=");
			builder.append(echostr);
		}
		builder.append("]");
		return builder.toString();
	}

	/**
	 * @return the signature
	 */
	public String getSignature() {
		return signature;
	}

	/**
	 * @param signature
	 *            the signature to set
	 */
	public void setSignature(String signature) {
		this.signature = signature;
	}

	/**
	 * @return the timestamp
	 */
	public String getTimestamp() {
		return timestamp;
	}

	/**
	 * @param timestamp
	 *            the timestamp to set
	 */
	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	/**
	 * @return the nonce
	 */
	public String getNonce() {
		return nonce;
	}

	/**
	 * @param nonce
	 *            the nonce to set
	 */
	public void setNonce(String nonce) {
		this.nonce = nonce;
	}

	/**
	 * @return the echostr
	 */
	public String getEchostr() {
		return echostr;
	}

	/**
	 * @param echostr
	 *            the echostr to set
	 */
	public void setEchostr(String echostr) {
		this.echostr = echostr;
	}
}
